import nunjucks from 'nunjucks'
import fs from 'fs'
import path from 'path'


class TemplateEngine {

    constructor(onceData){
        this.onceData = onceData
    }

    render(){
        let env = nunjucks.configure(
            this.onceData.templateInfo.templatePath,  //模板存储路径
            {
                autoescape: false ,
                trimBlocks :true  //去掉代码块自动换行符号
            }
        );

        env.addFilter('split', function(str, delimter) {
            return str.split(delimter);
        });

        let result = nunjucks.render(
            this.onceData.templateInfo.templateName,   //模板文件名称
            {
                onceData: this.onceData,   //一次生成需要的所有数据
                tableName: this.onceData.tableName,
                tableComment: this.onceData.tableComment,
                camelTableName: this.onceData.camelTableName,
                capitalizeCamelTableName: this.onceData.capitalizeCamelTableName,
                flatTableName: this.onceData.flatTableName,//传递模板文件所需的数据
                camelFields: this.onceData.camelFields,
                queryParamFields: this.onceData.queryParamFields,
                showInTableFields: this.onceData.showInTableFields,
                addEditedFields: this.onceData.addEditedFields,
            }
        );

        fs.writeFileSync(path.join(
            this.onceData.templateInfo.targetPath
            ,this.resolveTargetFileName(this.onceData.templateInfo.targetName)
            ),
        result)
    }

    //解析最终生成的文件(含占位符)
    resolveTargetFileName(fileRawName){
        return nunjucks.renderString(fileRawName, {
                tableName: this.onceData.tableName,
                capitalizeCamelTableName: this.onceData.capitalizeCamelTableName
        })
    }
}


export default TemplateEngine



